<script lang="ts" setup>
import { between } from '@/lib/util';
import { toRefs } from 'vue';

const props = (defineProps<{
  disabled: boolean,
  leftRange: [number, number],
  rightRange: [number, number]
}>())
const { disabled, leftRange, rightRange } = toRefs(props)
const emit = defineEmits(['resized', 'resizing', 'resize-start'])
let x = 0
let t = 'left'
const mousemove = (e: MouseEvent) => {
  const range = t === 'left' ? leftRange : rightRange
  const movment = between(e.x - x, ...range.value)
  emit('resizing', t, movment)
}
const mouseup = (e: MouseEvent) => {
  const range = t === 'left' ? leftRange : rightRange
  const movment = between(e.x - x, ...range.value)
  emit('resizing', t, movment)
  emit('resized')
  window.removeEventListener('mousemove', mousemove)
  window.removeEventListener('mouseup', mouseup)
}
const mousedown = (e: MouseEvent, type: 'left' | 'right') => {
  x = e.x
  t = type
  e.preventDefault()
  emit('resize-start')
  emit('resizing', t, 0)
  window.addEventListener('mousemove', mousemove)
  window.addEventListener('mouseup', mouseup)
}
</script>

<template>
  <div class="resizer-container rel">
    <div class="left resizer abs" @mousedown="mousedown($event, 'left')" v-show="!disabled"></div>
    <slot></slot>
    <div class="right resizer abs" @mousedown="mousedown($event, 'right')" v-show="!disabled"></div>
  </div>
</template>

<style lang="stylus">
.resizer-container
  position: relative
  .resizer
    top: 0;
    position: absolute;
    height: 100%;
    cursor: ew-resize;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 9px;
    border: 3px solid #fff;
  .left
    left: 0;
    border-right: transparent
  .right
    right: 0;
    border-left: transparent
</style>
